<?php
/**
 * Created by PhpStorm.
 * User: xuke
 * Date: 16/6/7
 * Time: 下午5:38
 */

namespace App\Logic;
use App\Http\Model\Device AS DeviceModel;
use App\Exceptions\ApiException;

class Device extends BaseLogic
{
    private $_device = null;

    public function __construct($device)
    {
        $this->_device = $device;
    }

    /**根据设备号,返回对应设备logic
     * @param $device 设备号
     */
    public static function initByDevice($device)
    {
        if ($device instanceof Device)
        {
            $_deveice = $device;
        }else if(is_string($device)) {
            $_deveice = DeviceModel::where('uuid', $device)->first();
        }

        if (empty($_deveice))
        {
            throw new ApiException('设备信息错误', 1003);
        }

        return new static($_deveice);
    }
    
    public static function create()
    {
        $device = new DeviceModel();
        return new static($device);
    }
    
    /**
     * 保存用户设备信息
     */
    public static function findAndSave($device)
    {
        $deviceModel = DeviceModel::where('uuid', $device['uuid'])->first();
        $re = true;
        if (empty($deviceModel))  //如果没有找到该设备信息,则直接保存
        {
            $deviceModel = new DeviceModel();
           $re = $deviceModel->fill($device)->save();
        }else{

            //如果设备号已经存在,但是用户操作系统已升级,或者运营商改变,则修改数据
            if($device['os_version'] != $deviceModel->os_version || $device['carrier'] != $deviceModel->carrier)
            {
                $re = $deviceModel->fill($device)->save();

            }
        }

        if(!$re) {
            throw new ApiException(-2, '设备信息保存失败');
        }

        return new static($device);
        
    }
    
}